package com.jingtai.shop.service.user.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jingtai.common.enums.CollectStatusEnum;
import com.jingtai.common.enums.DeleteFlagEnum;
import com.jingtai.common.webfacade.error.CommonException;
import com.jingtai.core.entity.member.MemberCollectStore;
import com.jingtai.core.entity.merchants.UserStore;
import com.jingtai.core.mapper.member.MemberCollectStoreMapper;
import com.jingtai.shop.service.goods.UserStoreService;
import com.jingtai.shop.service.user.MemberCollectStoreService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class MemberCollectStoreServiceImpl extends ServiceImpl<MemberCollectStoreMapper, MemberCollectStore> implements MemberCollectStoreService {

    @Resource
    private MemberCollectStoreService collectStoreService;
    @Resource
    private UserStoreService userStoreService;

    /**
     * 用户查看自己收藏的店铺列表
     */
    @Override
    public Page<MemberCollectStore> showCollectStore(Long userId, Long pageNo, Long pageSize) {
        return collectStoreService.page(new Page<>(pageNo, pageSize), Wrappers.lambdaQuery(MemberCollectStore.class)
                .eq(MemberCollectStore::getUserId, userId)
                .eq(MemberCollectStore::getIsCollect, CollectStatusEnum.COLLECTED.getStatus())
                .eq(MemberCollectStore::getDeleteFlag, DeleteFlagEnum.NOT_DELETE.getCode()));
    }

    /**
     * 点击收藏/取消店铺
     */
    @Override
    public boolean collectStore(Long storeId, Long userId, Integer collectStatus) {
        UserStore userStore = userStoreService.getOne(Wrappers.lambdaQuery(UserStore.class)
                .eq(UserStore::getId, storeId)
                .eq(UserStore::getDeleteFlag, DeleteFlagEnum.NOT_DELETE.getCode()));
        if (ObjectUtil.isEmpty(userStore)){
            throw new CommonException("暂未查到该店铺!");
        }
        //查询历史收藏记录
        MemberCollectStore one = collectStoreService.getOne(Wrappers.lambdaQuery(MemberCollectStore.class).eq(MemberCollectStore::getStoreId, storeId).eq(MemberCollectStore::getUserId, userId));
        if (ObjectUtil.isEmpty(one)){
            MemberCollectStore memberCollectStore = new MemberCollectStore();
            memberCollectStore.setUserId(userId);
            memberCollectStore.setStoreId(storeId);
            memberCollectStore.setMerchantsId(userStore.getUserId());
            memberCollectStore.setStoreName(userStore.getStoreName());
            memberCollectStore.setStoreLogo(userStore.getStoreLogo());
            memberCollectStore.setIsCollect(collectStatus);
            return collectStoreService.save(memberCollectStore);
        }else {
            one.setIsCollect(collectStatus);
            return collectStoreService.updateById(one);
        }

    }
}
